package org.budo.excel.jdbc.driver;

import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.budo.excel.jdbc.driver.executor.ExcelStatementExecutor;
import org.budo.excel.jdbc.driver.executor.PoiExcelStatementExecutor;
import org.budo.jdbc.driver.AbstractBudoJdbcConnection;
import org.budo.jdbc.driver.statement.JdbcStatement;

/**
 * @author lmw
 */
public class BudoExcelJdbcConnection extends AbstractBudoJdbcConnection {
    private  ExcelStatementExecutor  _statementExecutor;

    /**
     * 延迟初始化 ExcelStatementExecutor
     */
    public ExcelStatementExecutor statementExecutor() {
        if (null != this._statementExecutor) {
            return this._statementExecutor;
        }

        synchronized (this) {
            if (null != this._statementExecutor) {
                return this._statementExecutor;
            }

            return this._statementExecutor = new PoiExcelStatementExecutor(this.jdbcUrl());
        }
    }

    @Override
    public Statement createStatement() throws SQLException {
        return new BudoExcelJdbcStatement() //
                .setConnection(this);
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return new BudoExcelJdbcDatabaseMetaData() //
                .connection(this);
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        JdbcStatement jdbcStatement = this.statementParser().parse(sql);

        return (PreparedStatement) new BudoExcelJdbcPreparedStatement() //
                .setJdbcStatement(jdbcStatement) // 
                .setConnection(this);//
    }
}